﻿using Newtonsoft.Json;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

using System.Data;
using System.Reflection;

namespace PLCS.Shared.Common.Helper;

public static class TableHelper
{
    /// <summary>
    /// Excel导入成DataTble
    /// </summary>
    /// <param name="file">导入路径(包含文件名与扩展名)</param>
    /// <returns></returns>
    public static DataTable ExcelToTable(string file, int index = 0)
    {
        DataTable dt = new DataTable();
        IWorkbook workbook;
        string fileExt = Path.GetExtension(file).ToLower();
        if (string.IsNullOrEmpty(file)) return null;
        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
        {
            if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
            if (workbook == null) { return null; }
            ISheet sheet = workbook.GetSheetAt(index);

            //表头
            IRow header = sheet.GetRow(sheet.FirstRowNum);
            List<int> columns = new List<int>();
            for (int i = 0; i < header.LastCellNum; i++)
            {
                object obj = GetValueType(header.GetCell(i));
                if (obj == null || obj.ToString() == string.Empty)
                {
                    dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                }
                else
                    dt.Columns.Add(new DataColumn(obj.ToString()));
                columns.Add(i);
            }
            //数据
            for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
            {
                DataRow dr = dt.NewRow();
                bool hasValue = false;
                foreach (int j in columns)
                {
                    dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                    if (dr[j] != null && dr[j].ToString() != string.Empty)
                    {
                        hasValue = true;
                    }
                }
                if (hasValue)
                {
                    dt.Rows.Add(dr);
                }
            }
        }
        return dt;
    }

    public static void TableToExcel(DataTable dataTable, string filePath, string sheetName, int index)
    {
        IWorkbook workbook;

        // 检查文件是否存在
        if (File.Exists(filePath))
        {
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                // 读取现有的 Excel 文件
                workbook = new HSSFWorkbook(fileStream);
            }
        }
        else
        {
            // 创建一个新的 Excel 文件
            workbook = new HSSFWorkbook();
        }

        // 检查工作表是否存在
        ISheet sheet = workbook.GetSheet(sheetName);
        if (sheet != null)
        {
            // 如果工作表已经存在，则直接使用现有的工作表
            sheet = workbook.GetSheetAt(workbook.GetSheetIndex(sheet));
            // 获取工作表的所有行，并逐行删除
            for (int rowIndex = sheet.LastRowNum; rowIndex >= 0; rowIndex--)
            {
                IRow row = sheet.GetRow(rowIndex);
                if (row != null)
                    sheet.RemoveRow(row);
            }
        }
        else
        {
            // 如果工作表不存在，则插入一个新的工作表
            if (index >= workbook.NumberOfSheets)
            {
                sheet = workbook.CreateSheet(sheetName);
            }
            else
            {
                sheet = workbook.CloneSheet(index);
                workbook.SetSheetName(index, sheetName);
                workbook.SetSheetOrder(sheetName, index);
            }
        }

        // 创建表头行，并将列名写入 Excel 中
        var headerRow = sheet.CreateRow(0);
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            var cell = headerRow.CreateCell(i);
            cell.SetCellValue(dataTable.Columns[i].ColumnName);
        }

        // 将 DataTable 的数据写入 Excel 中
        for (int i = 0; i < dataTable.Rows.Count; i++)
        {
            var dataRow = sheet.CreateRow(i + 1);
            for (int j = 0; j < dataTable.Columns.Count; j++)
            {
                var cell = dataRow.CreateCell(j);
                cell.SetCellValue(dataTable.Rows[i][j].ToString());
            }
        }

        // 保存 Excel 文件
        using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        {
            workbook.Write(fileStream, true);
        }
    }

    public static string ExcelToJson(string file)
    {
        var table = ExcelToTable(file);
        return JsonConvert.SerializeObject(table);
    }

    /// <summary>
    /// 获取单元格类型
    /// </summary>
    /// <param name="cell">目标单元格</param>
    /// <returns></returns>
    private static object GetValueType(ICell cell)
    {
        if (cell == null)
            return null;
        switch (cell.CellType)
        {
            case CellType.Blank:
                return null;

            case CellType.Boolean:
                return cell.BooleanCellValue;

            case CellType.Numeric:
                return cell.NumericCellValue;

            case CellType.String:
                return cell.StringCellValue;

            case CellType.Error:
                return cell.ErrorCellValue;

            case CellType.Formula:
            default:
                return "=" + cell.CellFormula;
        }
    }
}